import { Component, OnInit } from '@angular/core';
import { PushMessage } from '../../domain/pushMessage';
import { PushMessageService } from '../../service/pushmessage.service';
import { Toastr } from '../../common/toastr';
import { UserService, UserQueryParameter } from '../../service/user.service';
import { User } from '../../domain/user';

@Component({
    moduleId: module.id,
    templateUrl: 'pushMsg.component.html'
})
export class PushMessageComponent implements OnInit {
    private title: string = "推送消息";
    private subTitle: string = "发送推送消息到客户端";
    private pushMessage: PushMessage = new PushMessage();
    private userList: User[] = [];
    private queryParams: UserQueryParameter = {
        currentPage: 1,
        pageSize: 10,
        userNick: "",
        phone: ""
    };
    private selectedUserList: User[] = [];

    constructor(
        private pushMgSvr: PushMessageService,
        private userSvr: UserService
    ) { }

    ngOnInit() {

    }

    async searchUser() {
        try {
            let r = await this.userSvr.GetUserList(this.queryParams);
            this.userList = r.list;
            console.log(this.userList);
        } catch (error) {
            Toastr.Error(error);
        }
    }

    async notifyMessage() {
        try {
            if (this.pushMessage.type == 1) {
                for (let item of this.selectedUserList) {
                    this.pushMessage.userList.push(item.userName);
                }
            }
            await this.pushMgSvr.NotifyMessage(this.pushMessage);
            Toastr.Success("消息发送成功！");
        } catch (error) {
            Toastr.Error(error);
        }
    }

    selectUser(item: User) {
        (<any>item).checked = !(<any>item).checked;
        if ((<any>item).checked) {
            this.selectedUserList.push(item);
        }
        else this.removeSelectedUser(item);
    }

    removeSelectedUser(item: User) {
        let index = this.selectedUserList.findIndex(x => x.userId == item.userId);
        if (index != null && index != undefined) {
            this.selectedUserList.splice(index, 1);
            delete (<any>item).checked;
        }
    }
}